package com.atguigu.servlet;

import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

/**
 * Date:2020/10/13
 * Author:ybc
 * Description:
 */
@WebServlet(name = "CodeSenderServlet", value = "/CodeSenderServlet")
public class CodeSenderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取请求参数
        String phone_no = request.getParameter("phone_no");
        //获取验证码
        String verifyCode = getVerifyCode();
        //设置redis存储验证码的键
        String codeKey = "verifyCode:"+phone_no+":code";
        //设置redis存储发送验证码次数的键
        String countKey = "verifyCode:"+phone_no+":count";
        //创建Jedis对象
        Jedis jedis = new Jedis("192.168.192.132", 6379);
        //根据自己的IP写：
        //判断验证码发送的次数
        String countStr = jedis.get(countKey);
        if(countStr == null){
            //当天第一次方法验证码
            jedis.setex(countKey, 24*60*60, "1");
        }else{
            int count = Integer.parseInt(countStr);
            if(count == 3){
                //当天已经发送三次，没有机会，响应浏览器limit
                response.getWriter().print("limit");
                jedis.close();
                return ;
            }else{
                //当发送次数为1次或2次，将次数+1
                jedis.incr(countKey);
            }
        }
        //存储验证码
        jedis.setex(codeKey, 120, verifyCode);
        //关闭jedis
        jedis.close();
        //响应客户端数据true
        response.getWriter().print(true);

    }

    protected String getVerifyCode(){
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            code += random.nextInt(10);
        }
        return code;
    }
}
